package com.example.api.websocket.utils;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WebSocketUtils {
    //存放websocket session
    public static final Map<String, Session> living_session_cache = new ConcurrentHashMap<>();

    //给所用用户发送消息
    public static void sendMessageAll(String message){
        living_session_cache.forEach((sessionId, session)->sendMessage(session, message));
    }

    //给指定用户发送消息
    public static void sendMessage(Session session, String message){
        if (null == session){
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (null == basic){
            return;
        }
        try {
            basic.sendText(message);
        } catch (IOException e) {
            log.error("发送WebSocket消息异常：" + e);
        }
    }
}
